package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Component
@Slf4j
public class RedisService {

        @Resource
        private StringRedisTemplate  stringRedisTemplate;

        public RedisService(StringRedisTemplate stringRedisTemplate) {
            this.stringRedisTemplate = stringRedisTemplate;
        }

        public void set(String key, Object value, Long time , TimeUnit unit) {
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value) , time , unit);
        }

    public void setWithLogicalExpire(String key, Object value, Long time , TimeUnit unit) {
            //设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        //写入Redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R,ID> R queryWithPassThrough(String KeyPrefix , ID id, Class<R> type, Function<ID , R > dbFallback, Long time , TimeUnit unit){
        //TODO 1.从redis查询商铺缓存
        String key = KeyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //TODO 2.判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //TODO 3.存在，直接返回（缓存命中）

            return JSONUtil.toBean(json,type);
        }
        //判断命中的是否为空值
        if (json != null){
            //返回错误信息
            return  null;
        }

        //TODO 4.redis中不存在，根据id查数据库，没有则返回错误
        R r = dbFallback.apply(id);
        if (r == null) {
            //1.（解决缓存穿透）将空值写入redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "",CACHE_NULL_TTL, TimeUnit.MINUTES);
            //2.返回错误信息
            return null;
        }
        //TODO 5.有则写入redis
        this.setWithLogicalExpire(key , r ,time,unit);
        //TODO 6.返回
        return r;
    }


    public <R , ID> R queryWithLogicalExpire(String KeyPrefix ,ID id , Class<R> type ,Function<ID,R> dbFallback, Long time , TimeUnit unit){
        //TODO 1.从redis查询商铺缓存
        String key = KeyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //TODO 2.判断是否存在
        if (StrUtil.isBlank(json)) {
            //TODO 3.不存在，直接返回（缓存未命中）
            return null;
        }
        //TODO 4.redis中存在，json反序列化成对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data =(JSONObject)redisData.getData();
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期 返回店铺信息
            return r;
        }
        //已过期 缓存重建（获取互斥锁，判断是否获取锁成功）
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock){
            //TODO 成功，开启独立线程实现缓存重建 返回过期店铺信息
            CACHE_REBUILD_EXECUTOR.submit(()->{
                //重建缓存
                try {
                    //查询数据库
                    R r1 = dbFallback.apply(id);
                    //再写入redis

                    this.setWithLogicalExpire(key , r1 , time ,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unlock(lockKey);
                }
            });
            return r;
        }


        //失败，直接返回过期店铺信息


        //TODO 6.返回过期店铺信息
        return r;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key,"1",10,TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
}
